<?php
namespace Modules\Groupon\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\UnionOrder;
use Modules\Product\Entities\Sku;

use Modules\Order\Entities\ProductOrder as Order;

use Modules\Groupon\Entities\GrouponRecord;
use Modules\Groupon\Entities\GrouponSku;

use Validator;
use ThrowException;
use Auth;
use Payment;
use DB;

class GrouponOrderController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'skus' => ['required', 'array'],
            'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $isNeedAddress = 1;
        $address = null;

        // 是否拼团
        $grouponRecord = null;
        if ($req->input('groupon_record_id')) {
            $grouponRecord = GrouponRecord::getEntity([
                'id' => $req->groupon_record_id
            ]);
            $grouponRecord->isCanJoin($user) || ThrowException::Conflict('当前暂无法参与此拼团');
        }

        $grouponSku = GrouponSku::getEntity([
            'id' => $req->input('skus')[0]['id'],
            'with' => ['groupon', 'base_sku']
        ]);

        $sku = $grouponSku->base_sku ?: ThrowException::Conflict('sku不存在');
        $total = $req->input('skus')[0]['total'];
        $sku->isCanBuy($user, $total);

        $skuableMaps = [
            [
                'skuable' => $grouponSku,
                'total' => $total
            ]
        ];

        // 准备收货地址(如果有)
        $address = $user->getAddress($req->input('address_id'));

        $options = [
            'client_name' => Auth::clientName(),
            'client_type' => Auth::clientType(),
            'os_type' => Auth::osType(),
        ];

        // $unionOrder = UnionOrder::initWith($skuableMaps, $user, $address, $options);

        // 准备优惠券
        $userCoupon = $user->coupons()->valid()->where('id', $req->input('coupon_id'))->first();

        DB::beginTransaction();

        $order = Order::initWith($skuableMaps, $user, $address, [
            'is_hidden' => 1,
            'remark' => $req->input('remark'),
            'coupon' => $userCoupon
        ]);

        if ($order->isNeedAddress && !$address)
            ThrowException::Conflict('请选择收货地址');

        $order->createAll();

        if (!$grouponRecord) {
            $grouponRecord = GrouponRecord::createWith($order, $grouponSku->groupon);
        }
        else {
            $grouponRecord->addMember($user, $order);
        }

        $order->update([
            'groupon_record_id' => $grouponRecord->id,
            'activity_type' => 2,
        ]);

        // $order->completePay([]);
        // \Log::error($grouponRecord->uuid);
        // \Log::error($order->id);

        DB::commit();

        $res = [
            'order' => [
                'id' => $order->id,
                'uuid' => $order->uuid
            ],
            'groupon_record' => [
                'id' => $grouponRecord->id,
                'uuid' => $grouponRecord->uuid
            ]
        ];

        // if ($req->input('payment') === 'miniapp') {
        //     $clientName = Auth::clientName();

        //     $res['payment']['config'] = Payment::wechatPay($clientName, 'miniapp')->config($user, $unionOrder);
        // }

        return $res;
    }
}
